//
// Created by DengLibin on 2018/12/8 0008.
//
/*
 *  栈操作
 * */
#include <stdio.h>
#include <stdlib.h>
#include "../header/utf2gbk.h"
#define N 50 //不能取地址,不能赋值,由CPU产生
//结构体 栈
typedef struct stack
{
    int top;     //栈顶位置
    int data[N]; //数据
} STACK;
//是否为空
int isEmpty(STACK *stack)
{
    if (stack->top == -1)
    {
        return 1;
    }
    return 0;
}
//是否已满
int isFull(STACK *stack)
{
    if (stack->top == N - 1)
    {
        return 1;
    }
    return 0;
}

//设为空
void setEmpty(STACK *stack)
{
    stack->top = -1;
}
//压栈
int push(STACK *stack, int data)
{
    if (isFull(stack))
    {
        print_utf8_2_gbk("栈已满\n");
        return -1;
    }
    stack->top += 1;
    stack->data[stack->top] = data;
}
//弹栈
int pop(STACK *stack)
{
    if (isEmpty(stack))
    {
        print_utf8_2_gbk("栈已空\n");
        return -1;
    }
    int num = stack->data[stack->top];
    stack->top -= 1;
    // printf("top=%d\n",stack->top);
    return num;
}
void test()
{
    print_utf8_2_gbk("栈结构体类型大小:");
    printf("%d\n", sizeof(STACK));
    print_utf8_2_gbk("分配内存，并初始化:\n");
    STACK *stack = (STACK *)calloc(1, sizeof(STACK)); // calloc分配内存： 元素个数 元素大小
    if (stack == NULL)
    {
        print_utf8_2_gbk("内存分配失败\n");
        return;
    }
    print_utf8_2_gbk("内存分配成功,地址为:");
    printf("%p\n", stack);
    setEmpty(stack);
    //压栈
    for (int i = 0; i < N; i++)
    {
        print_utf8_2_gbk("压入数据:");
        printf("%d\n", i);
        push(stack, i);
    }
    //弹栈
    while (!isEmpty(stack))
    {
        print_utf8_2_gbk("弹栈:");
        printf("%d\n", pop(stack));
    }
    //释放内存
    free(stack);
}

int main1(int agc, char *argv[])
{

    test();
    return 0;
}
